c++ - 面向对象编程,使用静态函数统计对象

标签 c++ class oop static-members

我想用一个静态函数显示类的对象和对象的个数。我输入了这段代码,但它不起作用。它给出错误 Too many types indeclaration” 和 “undefined symbol getCount。谁能帮我?这段代码实际上哪里出错了?

#include<iostream>
#include<string>

class Bag {
private:
    static int objectCount;
    int Weight;
    std::string Brand;
    std::string Type;
    std::string Material;
    std::string Colour;
public:
    Bag(int W, std::string B, std::string T, std::string M, std::string C) {
        Weight = W;
        Brand = B;
        Type = T;
        Material = M;
        Colour = C;
        objectCount++;
    }

    void print() {
        std::cout << "\n";
        std::cout << "Bag: \n\n";
        std::cout << "Weight:\t\t" << Weight   << "kg" << '\n';
        std::cout << "Brand:\t\t"  << Brand    << '\n' << "Type:\t\t"   << Type   << '\n';
        std::cout << "Material:\t" << Material << '\n' << "colour:\t\t" << Colour << std::endl;
    }

    static int getCount() {
        return objectCount;
    }
};

int Bag::objectCount = 0;

int main() {
    Bag bag_1(2, "Slazanger", "Atheletic Bag", "Polyethylene", "Brown");
    bag_1.print();
    std::cout << "object count " << Bag::getCount() << '\n';

    Bag bag_2(4, "Samsonite", "Travel Bag", "Synthetic Fibre", "Gray");
    bag_2.print();
    std::cout << "object count " << Bag::getCount() << '\n';

    Bag bag_3(5, "Herschel", "Duffel bag", "Leather", "Black");
    bag_3.print();
    std::cout << "object count " << Bag::getCount() << '\n';

    Bag bag_4(3, "Kewin Woods", "Hand Bag", "Fibre", "Blue");
    bag_4.print();
    std::cout << "object count " << Bag::getCount() << std::endl;

    while(!std::cin.get());
    return 0;
}

最佳答案

您对它的范围界定不正确,getCount 是静态范围内的翻译 单位,不是类(class)。因此它没有可用的名为 objectCount 的符号。

要修复它,只需将方法放在类中即可。

class Bag {
private:
    static int objectCount;
    int Weight;
    string Brand,Type,Material,Colour;
public:
    Bag(int W ,string B ,string T,string M,string C)
    {
        Weight=W;
        Brand=B;
        Type=T;
        Material=M;
        Colour=C;

        objectCount++;
    }

    void print()
    {
        cout<<"\n";
        cout<<"Bag: \n\n";
        cout<<"Weight:\t\t"<<Weight<<"kg"<<endl;
        cout<<"Brand:\t\t"<<Brand<<endl<<"Type:\t\t"<<Type<<endl;
        cout<<"Material:\t"<<Material<<endl<<"colour:\t\t"<<Colour<<endl;
    }

   static int getCount()
   {
       cout<< objectCount;
   }
};

此外,Borland 是一个非常古老的编译器,令人惊讶的是它仍然 听到它的名字,上一次发布是大约 15 年前所以你真的应该 考虑使用 clanggccmsvc 并将您的学习 Material 升级到 不太古老的东西。在实践方面已经发生了很多变化, 标准和编译器一致性。

例如,C++ 头文件没有扩展名,诸如此类的其他小东西。

关于c++ - 面向对象编程,使用静态函数统计对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23185943/

相关文章:

c++ - 如何实现对序列对进行操作的 C++ 元函数

c++ - OpenCV - 在 cvtColor 之后使用 ROI

c++ - 常量方法指针的类型是什么?

c++ - 处理许多自定义异常的最佳方法是什么

c# - 有什么方法可以像 php 一样在 C# 中创建标准类和对象

C++:在链表中查找类的最大值

php - 我应该延长这门课吗? (PHP)

php - 从存储在另一个类中的实例访问类常量

C++:结构的构造函数?

php - 为什么覆盖方法参数违反了 PHP 中的严格标准?