【问题标题】:Cannot call member function std::string class::function() without object不能在没有对象的情况下调用成员函数 std::string class::function()
【发布时间】:2013-10-02 07:08:05
【问题描述】:

我知道以前似乎有人问过这个问题,但我环顾四周,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();}

因此我很困惑为什么一个有效而另一个无效。

编辑:好的,我明白了,我刚刚意识到我在函数定义中调用了另一个结构的函数,该函数定义是不同类的一部分。我明白了,谢谢所有回答的人

【问题讨论】:

  • 它是不是 静态的,你应该通过一个对象来调用它。
  • 正如所指出的,您错过了将函数声明为静态的,因此错误。你能把原始代码放在“静态”不适合你的地方吗?
  • @NotAgain 确定是这个 'struct Customer { public: static string get_name();私人:字符串客户,第一,最后; };'
  • 让我猜猜。您编写了一个静态函数 get_name() 并尝试返回字符串 customer、first 或 last 的内容。那是行不通的,因为静态成员函数只能访问类的静态数据。而且这三个字符串数据成员都不是静态的。

标签: c++ string function object


【解决方案1】:

未声明static(需要为static std::string get_name();)。但是,get_name() for CustomerCustomer 实例的特定属性,因此拥有它 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";

【讨论】:

  • 谢谢,我试图避免传递一个对象,但我想一个空对象对我的目的也是一样的。
【解决方案2】:

由于您的get_name 未声明为静态的,因此它是一个成员函数。

您的Customer 类中可能需要一些构造函数。假设你有一些,你可以编码

 Customer cust1("foo123","John","Doe");
 string name1 = cust1.get_name();

你需要一个对象(这里是cust1)来调用它的get_name成员函数(或方法)。

花很多时间阅读一本好的 C++ 编程书籍。

【讨论】:

    【解决方案3】:

    static 方法对我不起作用”。这不是一种方法,而是语言的工作方式。

    如果你想调用一些没有具体对象的方法,你需要它是静态的。否则,您需要一个对象。

    您的代码将与以下之一一起使用:

    struct Customer {
    public:
        static string get_name();
    private:
        string customer,first, last;
    };
    

    void creation::new_account() {
        Customer c;
        //stuff
        c.get_name();
    }
    

    【讨论】:

    • 对不起,我输入了方法,但除了语义之外,我的意思是我输入了静态字符串 get_name();编译器抱怨。但感谢第二个工作。我感到困惑的原因是因为我定义并声明了其他两个函数,并且我创建了另一个函数只是为了确保没有该函数它编译得很好。
    • @Shilaly 如果编译器在您实际使用static string get_name(); 时抱怨,那么您在其他地方又犯了一个错误...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多