如何从c++中的类开始

How to start with Classes in c++

本文关键字:开始 c++      更新时间:2023-10-16

我在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);
}
  1. 正如Arun A.S所说,在类定义中增加孔隙比
  2. 不能在increment函数中更改A.topSecret,因为您按值获取对象,所以您只更改临时对象,而使用void increment(myClass&A,int i)