c++ - 如何在“=”运算符的帮助下在 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++ 中实现,如果可以,那么如何实现。我正在考虑运算符重载,但我无法实现目标。任何人都可以请建议。
解决方案
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.
推荐阅读
- python - pyspark中的枢轴数据框
- cmd - 如何运行特定的 cmd.exe 以获得所需的结果?
- android - 在本地通过nodejs服务器发布android GPS位置?
- mapbox - Mpabox GL case 表达式输出,执行数学表达式
- regex - 正则表达式:如何强制可选组匹配
- finite-automata - 在自动机中使用字母表
- python - 如何从只有一个值的列表中拆分多个数字
- python - 用向量化方式从函数创建带有 numpy 的矩阵?
- python-3.x - Python Aliexpress API promoLinkGenerate
- arrays - 在 Google 表格中乘以嵌套的 IF