注意 - 我是新手,这是我在 S.Overflow 上的第一个问题。
我正在测试这些限制,并试图更清楚地理解所有这些编程语法。
当我尝试构建并运行它时,它不起作用。当我只需输入类名时,为什么要创建一个对象?
#include <iostream>
using namespace std;
class Sayings{
public:
void coolSaying(){
cout << "Preachin to the choir" << endl;
}
};
int main()
{
Sayings.coolSaying();
}
最佳答案
如果不想实例化对象,可以使用静态方法。但是,拥有对象实例的优势意味着您可以使用不同的数据创建同一类的多个实例。
#include <iostream>
#include <string>
using namespace std;
class Sayings{
public:
static void coolSaying(){
cout << "Preachin to the choir" << endl;
}
};
int main()
{
Sayings::coolSaying();
}
作为类实例有用性的示例:
#include <iostream>
using namespace std;
class Sayings{
public:
Sayings(const std::string & saying) : saying_(saying) {
}
void coolSaying(){
cout << saying_ << endl;
}
private:
std::string saying_;
};
int main()
{
Saying s1("Preachin to the choir");
Saying s2("Cool story bro");
s1.coolSaying();
s2.coolSaying();
}
关于c++ - 我是否必须创建一个对象来调用类方法,或者我可以只输入类名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17509275/