如何从c++中的类开始
How to start with Classes in c++
我在C++的类和对象中,在理解类的减速概念时遇到了困难,为此我制作了一个不编译的小程序,有人会指导我吗?
#include <iostream>
using namespace std;
class myClass{
friend increment(myClass, int);
private:
int topSecret;
public:
myClass(){
topSecret = 100;
}
void display(){
cout<<"The value of top Secter is"<<topSecret;
}
};
void increment(myClass A, int i){
A.topSecret += i;
}
int main() {
myClass x;
x.display();
increment(x,10);
x.display();
}
更改
friend increment(myClass, int);
至
friend void increment(myClass &, int);
这应该可以修复编译错误。
要修改传递给函数的原始对象,请声明函数引用:
void increment(myClass A, int i){
至
void increment(myClass &A, int i){
Arun的答案向您展示了如何修复编译错误,但这不是设计类的方式。定义非成员好友函数来访问您的内部数据通常会导致维护问题和错误。最好将increment
声明为公共成员函数,或者为类定义getter和setter:
class myClass{
private:
int topSecret;
public:
//use initialization list instead of setting in constructor body
myClass() : topSecret(100) {}
//getter, note the const
int GetTopSecret() const { return topSecret; }
//setter, non-const
void SetTopSecret(int x) { topSecret = x; }
//member version
void increment (int i) { topSecret += i; }
};
//non-member version with setter
//note the reference param, you were missing this
void increment(myClass &A, int i){
A.SetTopSecret(A.GetTopSecret() + i);
}
- 正如Arun A.S所说,在类定义中增加孔隙比
- 不能在increment函数中更改A.topSecret,因为您按值获取对象,所以您只更改临时对象,而使用void increment(myClass&A,int i)
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 如何从头开始创建 avi 文件?
- 为什么 -mmacosx-version-min=10.10 不阻止使用标记为从 10.11 开始的函数?
- 自一周开始以来的秒数?
- 一旦双簧管录制开始,主 UI 线程就会被阻止
- GStreamer在开始任何播放之前进行搜索
- 使 std::fstream 写入文件末尾,但从头开始读取
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 哪个C++规范开始支持 std::vector
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 如何在调试中通过传递引用开始
- 如何使用 picojson.h 在 c++ 中从头开始创建 json 对象
- 从特定键开始遍历地图
- 列表的有效性在插入后开始迭代器
- 尝试从头开始实现Leetcode的FizzBuzz多线程问题。收到"libc++abi.dylib: terminating"错误
- 试图修复一个错误,该错误不会让我开始编程其余部分
- 甚至在开始执行之前出现分段错误
- 为什么 Glib::VariantBase::store 方法破坏了给定缓冲区的开始