所以我得到了这个Exception
,我知道这只是因为我是新来的C++和我的代码是错误的(所以,不,这不是一个已经问过的问题)。在cout上的System.AccessViolationException << line
我得到了Frog.cpp
文件和program.cpp
文件。
Frog.cpp:
#include <iostream>
#include <conio.h>
#include "Frog.h"
using namespace std;
Frog::Frog()
{
(*this).status = Free;
(*this).color = "Green";
(*this).weight = 200; // In grams
}
Frog::Frog(float weight, int age, char* color, char* nickname, Status status)
{
(*this).weight = weight;
(*this).age = age;
(*this).color = color;
(*this).nickname = nickname;
(*this).status = status;
}
Frog::Frog(float weight, int age)
{
(*this).weight = weight;
(*this).age = age;
}
void Frog::currentState()
{
cout << "Weight:" << (*this).weight << " ,Age:" << (*this).age << " ,Color:" << (*this).color << " , Nickname:" << (*this).nickname << " , Status:" << (*this).status << endl; // The ling that causeing the mayhem
}
Frog.h:
#ifndef FROG_H
#define FROG_H
typedef enum Status { Free, Urban, Plate, Dead };
class Frog
{
private:
float weight;
int age;
char* color;
char* nickname;
Status status;
public:
Frog();
Frog(float weight, int age, char* color, char* nickname, Status status);
Frog(float weight, int age);
void currentState();
};
#endif
Program.cpp:
#include <iostream>
#include <conio.h>
#include "Frog.h"
using namespace std;
void main()
{
Frog frog = Frog();
frog.currentState(); // I get the Exception on this line
getch();
}
除外:
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at std.char_traits<char>.length(SByte* _First) in c:\program files (x86)\microsoft visual studio 12.0\vc\include\iosfwd:line 523
at std.operator<<<struct std::char_traits<char> >(basic_ostream<char\,std::char_traits<char> >* _Ostr, SByte* _Val) in c:\program files (x86)\microsoft visual studio 12.0\vc\include\ostream:line 791
at Frog.currentState(Frog*)
坏线cout << "Weight:" << (*this).weight << " ,Age:" << (*this).age << " ,Color:" << (*this).color << " , Nickname:" << (*this).nickname << " , Status:" << (*this).status << endl;
在Frog.cpp
。
任何建议将不胜感激。
OT:对于任何指针“foo”,您都可以写'foo-> bla'而不是'(* foo).bla'。 (也有几个非指针)。 –
你不检查的绰号是有效的,并没有将其设置为默认的构造函数的默认值。试图打印一个不指向有效c字符串的const char *是一个不同的错误计划。 – jaggedSpire
边注:请使用类初始化列表(和替换(*此)这个 - >) –