一个sizeof的问题!
代码如下:
Animal.h文件:
#ifndefANIMAL_H
#define ANIMAL_H
#include <string>
using std::string;
class Animal{
public:
virtual void who() const;
virtual string sound() const=0;
virtual ~Animal();
protected:
Animal(string n,int w);
string name;
int weight;
};
class Sheep:public Animal{
public:
Sheep(string n,int w);
virtual void who() const;
virtual string sound() const;
private:
string s;
};
class Dog:public Animal{
public:
Dog(string n,int w);
virtual void who() const;
virtual string sound() const;
private:
string s;
};
class Cow:public Animal{
public:
Cow(string n,int w);
virtual void who() const;
virtual string sound() const;
private:
string s;
};
class Zoo{
public:
Zoo();
void set(Animal* a[]);
void show(int n) const;
private:
Animal* pAnimal[50];
};
#endif
Animal.cpp文件:
#include "Animal.h "
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
Animal::Animal(string n,int w){
name=n;
weight=w;
}
void Animal::who() const{
cout < <name < < "的体重为: " < <weight;
}
Animal::~Animal(){}
Sheep::Sheep(string n,int w):Animal(n,w){
s= "mian mian mian ";
}
void Sheep::who() const{
cout < <name < < "的体重为: " < <weight;
}
string Sheep::sound() const{
return s;
}
Dog::Dog(string n,int w):Animal(n,w){
s= "wang wang wang ";
}
void Dog::who() const{
cout < <name < < "的体重为: " < <weight;
}
string Dog::sound() const{
return s;
}
Cow::Cow(string n,int w):Animal(n,w){
s= "wo wo wo ";
}
void Cow::who() const{
cout < <name < < "的体重为: " < <weight;
}
string Cow::sound() const{
return s;
}
Zoo::Zoo(){
for(int i=0;i <50;i++)
pAnimal[i]=0;
}
void Zoo::set(Animal* a[]){
for(int i=0;i <sizeof a/sizeof a[0];i++){
pAnimal[i]=a[i];
}
}
void Zoo::show(int n) const{
for(int i=0;i <n;i++){
pAnimal[i]-> who();
cout < < " 叫声是: " < <pAnimal[i]-> sound() < <endl;
}
}
main.cpp文件
#include <iostream>
using std::cout;
using std::endl;
#include "Animal.h "
int main(){
Animal* b[]={new Sheep ( "山羊 ",200),
new Sheep ( "绵羊 ",300),
new Dog ( "狼狗 ",80),
new Dog ( "狮子狗 ",20),
new Cow ( "奶牛 ",500),
new Cow ( "母牛 ",550),};
Zoo z;
z.set(b);
z.show(sizeof b/sizeof b[0]);
for(int i=0;i <sizeof b/sizeof b[0];i++)
delete b[i];
return 0;
}
运行出错。原因是:sizeof b是24,而sizeof a是4。b作为参数传递给a,那a和b应该一样嘛,怎么a比b小呢?请各位高手指点,谢谢!!!
[解决办法]
int a,*b;
sizeof(b)==sizeof(&a)!=sizeof(*b)==sizeof(a) 应该是这样的
b 的类型是int * 不是int