首页 > 解决方案 > 如何在“=”运算符的帮助下在 C++ 中传递参数

问题描述

我有一个名为的类Demo,在该类中,我重载了Text()用于设置和获取它的私有变量的方法text

#ifndef DEMO_H
#define DEMO_H

#include <string>
#include <iostream>

using namespace std;

class Demo {
    string text;

public:
    Demo() {};
    Demo(string newText) : text(newText) {};
    void Text(string updatedText);
    string Text();
};
#endif // !DEMO_H


void Demo::Text(string updatedText) {
    text = updatedText;
}

string Demo::Text() {
    return text;
}

然后在另一堂课中,我以以下方式使用了该方法-

#include "Demo.h"

int main()
{
    Demo d;
    d.Text("test");
    cout << d.Text() << endl;

    return 0;
}

这工作正常。但是,我想用“=”运算符设置方法的参数。所以而不是

d.Text("test");

我想要做

d.Text = "test";

是否有可能在 C++ 中实现,如果可以,那么如何实现。我正在考虑运算符重载,但我无法实现目标。任何人都可以请建议。

标签: c++methodsparametersoperator-overloading

解决方案


The closest you can get in c++ to express property like getter / setter functions similar as in c# is to provide class member functions like these:

class Demo {
    string text;

public:
    void Text(const string& updatedText) { text = updatedText; }
    const string& Text() const { return text; } 
};

That idiom is used a lot in the c++ standard library like here.


I want to do

d.Text = "test";

What you can do is

class Demo {
public:
    string& Text() { return text; }
};

and

d.Text() = "test";

but that totally defeats the concept of encapsulation of data.


推荐阅读