c++ - undefined reference c++ 丢失

标签 c++ reference undefined

#include "assert.h"; // for some reason assert wouldn't work on my compiler without this
#include <iostream>
#include <string>
#include <limits>   // This is helpful for inputting values. Otherwise, funny stuff happens


using namespace std;


class Product
{
public:

    Product();
    Product(string the_name, int the_price, int number_of);

    string return_name();
    void reduce_amount();
    void print_data() const;

private:
    string prod_name; // name of your product
    int price_in_cents; // it's price in cents
    int amount; // the number of the product that you have
};

Product::Product()
{

    prod_name = "NULL_NAME: NEED DATA";
    price_in_cents = 0;
}

Product::Product(string the_name, int the_price, int number_of)
{
    assert(the_price>0);
    assert(number_of>0);
    assert(number_of<21);
    assert(prod_name !="NULL_NAME: NEED DATA");
    prod_name = the_name;
    price_in_cents = the_price;
    amount = number_of;
}

void Product::print_data() const
{
    cout<<prod_name << endl;
    cout<<"The price in cents is: " <<price_in_cents<< endl;
    cout<< "Amount left: " << " " << amount << endl;
}

void Product::reduce_amount()
{
    amount = amount -1;
}


string Product::return_name()
{
    return prod_name;
}

class Vending_Machine
{
public:

    Vending_Machine();
    void empty_coins();
    void print_vend_stats();
    void add_product();
    Product buy_product();
private:
    int income_in_cents;

    Product product1();
    Product product2();
    Product product3();
    Product product4();
    Product product5();
};

void Vending_Machine::empty_coins()
{
    cout << "The total amount of money earned today is " << income_in_cents << " cents" << endl;
    income_in_cents = 0;
    cout << "All the coins have been withdrawn. The balance is now zero." <<     endl;
}

void Vending_Machine::print_vend_stats()
{

    cout<< "Total income thus far: " << income_in_cents << endl;

    if (product1().return_name() != "NULL_NAME: NEED DATA")
    {
        //stuff happens
    }
}

int main()
{
    return 0;
}

所以,我不确定我是否正确地完成了所有识别,但我在自动售货机 print_vend_stats() 函数中遇到 bool 语句问题。它是说我正在对 product1() 进行 undefined reference 。这是什么意思?

最佳答案

当你声明

Product product1();

您声明了一个成员函数,圆括号使它成为一个函数。

如果你去掉括号

Product product1;

您声明了一个成员变量,它是Product 类的实际实例。


另一个例子,你不会写例如

int income_in_cents();

现在要将 income_in_cents 声明为变量吗?

无论类型是像 int 这样的原始类型,还是像 Product 这样的类,都没有关系,成员变量的声明方式与您在其他任何地方所做的普通变量一样.

关于c++ - undefined reference c++ 丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30091190/

相关文章:

c++ - 有什么东西我可以用 C 做,但不能用 C++ 做吗?

c++ - 将指针传递给参数为引用的函数

javascript - 空值跳闸循环

c - *.hxx 中声明的 void 函数,在 *.cxx 中定义但在 *.c 中未定义

c++ - 使用 C++ 中的 vector 散列/映射自动聚类

c++ - 向 UnityWndClass 发送 "button pressed"消息

c++ - c++ 14 中的 vector<string> 或 vector<shared_ptr<string>>

java - 使用 "=="语句

c++ - 指针和引用问题(链表)

C 预处理器 : what is the motivation behind treating undefined macro as 0?