运行出现error C2872: 'cout' : ambiguous symbol该怎么解决

源代码如图


/*定义一个Animal类,
属性: weight,count
访问控制权限为保护类型
其中count为静态数据成员,用来记录animal的个数。

成员函数:
getCount() 用于获得属性count的值
void spark() 为纯虚函数

定义一个Dog类,以public方式继承Animal类
重写spark()函数,用于输出the dog  is wa wa wa!

定义一个Cat类,以public方式继承Animal类
重写spark()函数,输出the cat  is miao miao!

定义一个全局函数totalWeight(),用于计算一个Dog对象和一个Cat对象的重量和

要求程序运行结果为
the dog is wa wa wa
the cat is miao miao
共有 2 个动物
动物共 5 kg*/

//StudybarCommentBegin
//#include "iostream.h"
//补充待添加的代码,即4个类的定义,1个全局函数
//StudybarCommentEnd

#include <iostream>
using namespace std;
class Animal
{
protected:
    int weight;
    static int count;
public:
    Animal(){count ++;}
    static int getCount()
    {
        return count; 
    }
    virtual void spark()=0;
};
class Dog:public Animal
{
public:
    Dog(int w2){weight = w2;}
    int getWeight()
    {
        return weight;
    }
    virtual void spark(){cout << "the dog is wa wa wa" << endl;} 
};
class Cat:public Animal
{
public:
    Cat(int w1){weight = w1;}
    int getWeight()
    {
        return weight;
    }
    virtual void spark(){cout << "the cat is miao miao" << endl;}
};

int totalWeight(Dog &t, Cat &p )
{
    return t.getWeight()+p.getWeight();
}
//StudybarCommentBegin
int main()
{
    Dog d(2);
    d.spark();
    Cat c(3);
    c.spark();
    cout<<"共有 "<<c.getCount()<<" 个动物"<<endl;
    cout<<"动物共 "<<totalWeight(d,c)<<" kg"<<endl;
}

//StudybarCommentEnd

静态成员变量在类中仅仅是声明,没有定义,所以要在类的外面定义,实际上是给静态成员变量分配内存。

C++类的静态成员变量一定要初始化(分配内存)_wuxiaoxiao2021的博客-CSDN博客_类静态成员变量初始化 文章转载自https://my.oschina.net/u/1537391/blog/219432我们知道C++类的静态成员变量是需要初始化的,但为什么要初始化呢。其实这句话“静态成员变量是需要初始化的”是有一定问题的,应该说“静态成员变量需要定义”才是准确的,而不是初始化。两者的区别在于:初始化是赋一个初始值,而定义是分配内存。静态成员变量在类中仅仅是声明,没有定义,所以要在类的外面定义,实际... https://blog.csdn.net/vict_wang/article/details/80994894#:~:text=%E5%85%B6%E5%AE%9E%E8%BF%99%E5%8F%A5%E8%AF%9D%E2%80%9C%E9%9D%99%E6%80%81,%E9%9D%99%E6%80%81%E6%88%90%E5%91%98%E5%8F%98%E9%87%8F%E5%88%86%E9%85%8D%E5%86%85%E5%AD%98%E3%80%82

你需要在Animal类的定义后面定义Animal::count。

class Animal
{
protected:
    int weight;
    static int count;
public:
    Animal(){count++;}
    static int getCount()
    {
        return count; 
    }
    virtual void spark()=0;
};

int Animal::count=0; //定义并初始化count变量

试一下清理,再重新生成,有时候vs可能反应比较慢