繁体   English   中英

没有对象就无法调用成员函数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(); )。 然而, get_name()Customer是一个特定属性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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM