不能在没有对象的情况下调用成员函数 std::string class::function()
Cannot call member function std::string class::function() without object
我知道以前似乎有人问过这个问题,但我环顾四周,static
方法对我不起作用。这是我的代码:
struct Customer {
public:
string get_name();
private:
string customer,first, last;
};
这是我调用函数的地方:
void creation::new_account() {
Customer::get_name(); //line it gives the error on.
}
下面是一些编译良好的代码示例。
struct Creation { public: string get_date(); private: string date; };
那我叫它的方式是一样的
void Creation::new_account() { Creation::get_date();}
因此,我很困惑为什么一个有效而另一个无效。
编辑:好的,我明白了,我刚刚意识到我正在函数定义中调用另一个结构的函数,该函数定义是不同类的一部分。我明白了,感谢所有回答的人
它没有声明static
(需要static std::string get_name();
)。但是,Customer
的get_name()
是Customer
实例的特定属性,因此将其static
没有意义,这是所有 Customer
实例的相同名称。声明一个 Customer
对象并使用它。将名称提供给 Customer
的构造函数是有意义的,因为客户肯定不能没有名称而存在:
class Customer {
public:
Customer(std::string a_first_name,
std::string a_last_name) : first_name_(std::move(a_first_name)),
last_name_(std::move(a_last_name)) {}
std::string get_name();
private:
std::string first_name_;
std::string last_name_;
};
声明 Customer
的实例:
Customer c("stack", "overflow");
std::cout << c.get_name() << "n";
由于您的get_name
未声明为静态,因此它是一个成员函数。
Customer
类中可能需要一些构造函数。 假设你有一些,你可以编码
Customer cust1("foo123","John","Doe");
string name1 = cust1.get_name();
你需要一个对象(这里cust1
)来调用它的get_name
成员函数(或方法)。
是时候花很多时间阅读一本好的C++编程书了。
"
static
方法对我不起作用"。这不是一种方法,而是语言的工作方式。
如果你想在没有具体对象的情况下调用某个方法,你需要它是静态的。否则,您需要一个对象。
您的代码将用于以下其中一项:
struct Customer {
public:
static string get_name();
private:
string customer,first, last;
};
或
void creation::new_account() {
Customer c;
//stuff
c.get_name();
}
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- std::string, std::wstring and UTF8
- uan inplace replacement of std::string/std::wstring?
- #define Glib::string std:wstring
- 从 std::string & std::wstring 中获取 char 整数值
- BSTR转换为std::string(std::wstring),反之亦然