gpt4 book ai didi

c++ - 在 C++ 中,在类定义之内还是之外定义方法体更传统?

转载 作者:行者123 更新时间:2023-11-28 00:42:46 25 4
gpt4 key购买 nike

相当不言自明。我只是想知道在面向对象的 C++ 中更传统的做法是什么?

示例 A:

class CarObject{
private: //Local Variables
string name;
int cost;
public:
CarObject(string pName, int pCost){ //Constructor with parameters of car name and car cost
name = pName; //Sets the temporary variables to the private variables
cost = pCost;
}
void getDetails(){


cout << name;
cout << cost;

}//Public method that returns details of Car Object
};

示例 B:

class CarObject{
private: //Local Variables
string name;
int cost;
public:
CarObject(string pName, int pCost){ //Constructor with parameters of car name and car cost
name = pName; //Sets the temporary variables to the private variables
cost = pCost;
}
void getDetails(); //Public method that returns details of Car Object
};
void CarObject :: getDetails(){
cout << name;
cout << cost;
}

最佳答案

您的类定义通常在 .h 文件中,而您的方法和其他实现细节将在 .cpp 文件中。这在管理依赖项时提供了最大的灵 active ,防止在实现更改时进行不必要的重新编译,并且是大多数编译器和 IDE 所期望的模式。

主要的异常(exception)是:(1) inline 函数,它应该简短/简单,编译器可能会选择插入它来代替实际的函数调用,以及 (2) 模板,其实现取决于传递给它们的参数。

关于c++ - 在 C++ 中,在类定义之内还是之外定义方法体更传统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17914264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com