Please don’t confuse with the title as it was already asked by someone but for a different context
The below code in Visual C++ Compiler (VS2008) does not get compiled, instead it throws this exception:
std::ifstream input (fileName);
while (input) {
string s;
input >> s;
std::cout << s << std::endl;
};
But this code compiles fine in cygwin g++. Any thoughts?
tmlen
8,1744 gold badges31 silver badges83 bronze badges
asked Oct 27, 2009 at 14:49
0
Have you included all of the following headers?
<fstream>
<istream>
<iostream>
<string>
My guess is you forgot <string>
.
On a side note: That should be std::cout
and std::endl
.
answered Oct 27, 2009 at 15:07
sbisbi
217k45 gold badges254 silver badges439 bronze badges
12
Adding to @sbi answer, in my case the difference was including <string>
instead of <string.h>
(under VS 2017).
See the following answer: similar case answer
answered Mar 9, 2018 at 11:35
Guy AvrahamGuy Avraham
3,3723 gold badges40 silver badges49 bronze badges
In addition to what others said. The following code was necessary in my application to compile succesfully.
std::cout << s.c_str() << std::endl;
Another work-around to this is go to project properties -> General -> Character Set and choose «Ues Multi-Byte Character Set» (You won’t need to use c_str() to output the string)
There’s disadvantages to using MBCS so if you plan to localize your software, I’d advize against this.
answered Oct 24, 2018 at 16:10
Nick DelbarNick Delbar
1012 silver badges9 bronze badges
include <string>
Try including string header file along with <iostream>
file.
It will work in some compilers even without the <string>
because settings for different compilers are different and it is the compiler that is responsible for reading the preprocessor files that start with ‘#’ symbol to generate a obj file.
answered Aug 30, 2018 at 16:04
2
I’m required to write a function to overload the ==operator to compare width, height and colour. I need to return ‘Y’ if its equal and ‘N’ if its not.
This is my code which I think is correct, but keeps giving me the error:
error C2679: binary ‘<<‘ : no operator found which takes a right-hand operand of type ‘Rectangle’ (or there is no acceptable conversion)
I’ve searched for an answer and nothing came close to comparing 3 data as most examples are for comparing 2 datas.
#include <iostream>
#include <string>
using namespace std;
class Rectangle
{
private:
float width;
float height;
char colour;
public:
Rectangle()
{
width=2;
height=1;
colour='Y';
}
~Rectangle(){}
float getWidth() { return width; }
float getHeight() { return height; }
char getColour() { return colour; }
Rectangle(float newWidth, float newHeight, char newColour)
{
width = newWidth;
height = newHeight;
colour = newColour;
}
char operator== (const Rectangle& p1){
if ((width==p1.width) && (height==p1.height) && (colour==p1.colour))
return 'Y';
else
return 'N';
}
};
int main(int argc, char* argv[])
{
Rectangle rectA;
Rectangle rectB(1,2,'R');
Rectangle rectC(3,4,'B');
cout << "width and height of rectangle A is := " << rectA.getWidth() << ", " << rectA.getHeight() << endl;
cout << "Are B and C equal? Ans: " << rectB==rectC << endl;
return 0;
}
I’m required to write a function to overload the ==operator to compare width, height and colour. I need to return ‘Y’ if its equal and ‘N’ if its not.
This is my code which I think is correct, but keeps giving me the error:
error C2679: binary ‘<<‘ : no operator found which takes a right-hand operand of type ‘Rectangle’ (or there is no acceptable conversion)
I’ve searched for an answer and nothing came close to comparing 3 data as most examples are for comparing 2 datas.
#include <iostream>
#include <string>
using namespace std;
class Rectangle
{
private:
float width;
float height;
char colour;
public:
Rectangle()
{
width=2;
height=1;
colour='Y';
}
~Rectangle(){}
float getWidth() { return width; }
float getHeight() { return height; }
char getColour() { return colour; }
Rectangle(float newWidth, float newHeight, char newColour)
{
width = newWidth;
height = newHeight;
colour = newColour;
}
char operator== (const Rectangle& p1){
if ((width==p1.width) && (height==p1.height) && (colour==p1.colour))
return 'Y';
else
return 'N';
}
};
int main(int argc, char* argv[])
{
Rectangle rectA;
Rectangle rectB(1,2,'R');
Rectangle rectC(3,4,'B');
cout << "width and height of rectangle A is := " << rectA.getWidth() << ", " << rectA.getHeight() << endl;
cout << "Are B and C equal? Ans: " << rectB==rectC << endl;
return 0;
}
karlhildekruger 3 / 4 / 0 Регистрация: 09.05.2022 Сообщений: 110 |
||||||||
1 |
||||||||
05.06.2022, 21:27. Показов 850. Ответов 13 Метки нет (Все метки)
Ошибка: Код Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка C2679 бинарный "<<": не найден оператор, принимающий правый операнд типа "std::vector<stud::Student,std::allocator<stud::Student>>" (или приемлемое преобразование отсутствует) 204 геттер из класса Institute, который я пытаюсь сериализовать в текстовый файл
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
05.06.2022, 21:27 |
Ответы с готовыми решениями: Ошибка C2679: бинарный ‘=’: не найден оператор, принимающий правый операнд типа ‘double’ #include… Error C2679: бинарный «=»: не найден оператор, принимающий правый операнд типа Возвращение кортежа — error C2679: бинарный «=»: не найден оператор, принимающий правый операнд типа tuple<X**, Math, int, int,… Error C2679: бинарный «<<«: не найден оператор, принимающий правый операнд типа «std::string» (или приемлемое #include "stdafx.h" #include <iostream> Error C2679: бинарный «=»: не найден оператор, принимающий правый операнд 13 |
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
05.06.2022, 21:48 |
2 |
karlhildekruger, вам нужно определить оператор << для типа
0 |
karlhildekruger 3 / 4 / 0 Регистрация: 09.05.2022 Сообщений: 110 |
||||
05.06.2022, 22:23 [ТС] |
3 |
|||
Это правильно?
Выдает ошибку Код Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка C2679 бинарный "<<": не найден оператор, принимающий правый операнд типа "const _Ty" (или приемлемое преобразование отсутствует)
0 |
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
05.06.2022, 23:25 |
4 |
Это правильно? Правильно. И для Student тоже должен быть такой оператор.
Выдает ошибку В какой строке?
0 |
3 / 4 / 0 Регистрация: 09.05.2022 Сообщений: 110 |
|
05.06.2022, 23:35 [ТС] |
5 |
os << vect[i] << «t»; Ошибка в этой строке
0 |
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
05.06.2022, 23:59 |
6 |
Ошибка в этой строке …
для Student тоже должен быть такой оператор
0 |
karlhildekruger 3 / 4 / 0 Регистрация: 09.05.2022 Сообщений: 110 |
||||
06.06.2022, 00:12 [ТС] |
7 |
|||
Не работает. Выводит те же ошибки
0 |
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
06.06.2022, 00:13 |
8 |
Не работает. Значит вы что-то не так сделали.
0 |
karlhildekruger 3 / 4 / 0 Регистрация: 09.05.2022 Сообщений: 110 |
||||||||||||
06.06.2022, 00:16 [ТС] |
9 |
|||||||||||
Student.h
institute.h
serializer.h
0 |
2057 / 1615 / 532 Регистрация: 29.06.2020 Сообщений: 6,077 |
|
06.06.2022, 00:32 |
10 |
os << s.getStudentNo(); Эти методы у класса Student, не константные, а вы пытаетесь их вызвать от константного объекта. Добавлено через 2 минуты
string StudentNo = «123»; Улыбнуло )
0 |
DrOffset 16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
||||
06.06.2022, 00:40 |
11 |
|||
Выводит те же ошибки Ну, как минимум не те же.
Также у вас в реализации оператора << для Student используется константная ссылка (что правильно), но функции используемые внутри него
0 |
3 / 4 / 0 Регистрация: 09.05.2022 Сообщений: 110 |
|
06.06.2022, 01:43 [ТС] |
12 |
сделал для всех операторов определение, все сделал константными, появились другие ошибки Код Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка LNK2005 "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class stud::Student const &)" (??6@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AEAV01@AEBVStudent@stud@@@Z) уже определен в Main.obj C:УЧЕБАСРСSerializer.obj 1 Код Серьезность Код Описание Проект Файл Строка Состояние подавления Ошибка LNK1169 обнаружен многократно определенный символ - один или более 1
0 |
Вездепух 10435 / 5704 / 1553 Регистрация: 18.10.2014 Сообщений: 14,098 |
|
06.06.2022, 02:04 |
13 |
появились другие ошибки Ну так в ошибке же написано, в чем проблема. Скорее всего вы засунули определение оператора В заголовочный файл можно помещать только определения особых категорий 1. Определения шаблонов Ваш оператор
0 |
alecss131 Модератор 2383 / 955 / 335 Регистрация: 11.08.2017 Сообщений: 2,980 |
||||||||
06.06.2022, 11:18 |
14 |
|||||||
Зачем так сложно? можно короче
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
06.06.2022, 11:18 |
14 |
- Remove From My Forums
-
Question
-
When i am trying to port my project from visual studio 2006 to visual studio 2008, i am getting the following error
error C2679: binary ‘=’ : no operator found which takes a right-hand operand of type ‘util:oint *’ (or there is no acceptable conversion)
1> C:Program FilesMicrosoft Visual Studio 9.0VCincludevector(273): could be ‘std::_Vector_const_iterator<_Ty,_Alloc> &std::_Vector_const_iterator<_Ty,_Alloc>:perator =(const std::_Vector_const_iterator<_Ty,_Alloc> &)’
Can any one help me in resolving the error
Answers
-
Maybe you have to replace the last line with:
lp_Iterator = lpC_Line->Points.end();
-
Are you sure there are «()» after end in your last code? Maybe you also have to define your iterator as a constant one:
std:: vector<util:: Point>:: const_iterator lp_Iterator;
Hi everyone, I’m new to C++. I’ve been assigned the following tasks.
1. Choose any two random numbers in the range 3 to 9.
2. Find position of these random numbers for each row.
3. Swap these two random numbers for each row.
4. Display new vector after swapping.
I tried to solve it but error occurred.
Error:
error C2679: binary ‘<<‘: no operator found which takes a right-hand operand of type ‘std::vector<int,std::allocator<_Ty>>’ (or there is no acceptable conversion)
I don’t know how to fix it. Hopefully someone can help me. Thank you
|
|
Here:
|
|
The type of it is std::vector<std::vector<int>>::iterator, so the type of *it is std::vector<int>.
Are you sure the rest of the code in the loop does what you think it does? What it really does is not swap two numbers. It’s swapping two vectors; two rows, if you will.
Because you have a vector of vectors, your iterators are pointing to an entire vector of values, not a single value … so the << operator won’t know how to output them.
Perhaps you would like to explain exactly how you think «your» code works?
I think it would be easier to advise if you gave us VERBATIM the bit of your assignment BEFORE what you have quoted: we are only getting a very confused story and it is unclear what you are being asked.
HiHelios,
Are you sure the rest of the code in the loop does what you think it does? What it really does is not swap two numbers. It’s swapping two vectors; two rows, if you will.
Can’t I use iter_swap() function to swap numbers?
Hilastchance,
I think it would be easier to advise if you gave us VERBATIM the bit of your assignment BEFORE what you have quoted: we are only getting a very confused story and it is unclear what you are being asked.
Sorry for inconvenience. I was given a task to generate two random numbers between 3 to 9.
For example: first random number = 5 and second random number = 9.
Then, I need to find the position of these random number for each row vector as follow:
{ 9, 8, 7, 6, 5, 4, 3, 2, 1 } —> first random number = position 5, second random number = position 1
{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } —> first random number = position 5, second random number = position 9
{ 5, 4, 3, 2, 1, 9, 8, 7, 6 } —> first random number = position 1, second random number = position 6.
Then, swap these random numbers for each row
{ 9, 8, 7, 6, 5, 4, 3, 2, 1 } —> { 5, 8, 7, 6, 9, 4, 3, 2, 1 }
{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } —> { 1, 2, 3, 4, 9, 6, 7, 8, 5 }
{ 5, 4, 3, 2, 1, 9, 8, 7, 6 } —> { 9, 4, 3, 2, 1, 5, 8, 7, 6 }
You need to deal with each vec[i] in turn, not the whole of vec.
I presume you know whether the number refers to the value or its position.
Last edited on
Hi lastchance,
You need to deal with each vec[i] in turn, not the whole of vec.
Does it mean I need to deal with each column not each row.
Sorry for asking. A bit confusing..
Does it mean I need to deal with each column not each row.
You need to deal with both.
sarah1993 wrote: |
---|
Does it mean I need to deal with each column not each row. |
You need to deal with the i’th row (that, is, vec[i]) inside the i loop.
|
|
needs to be
|
|
with a whole mass of other changes from vec to vec[i] below it.
For your final output either move it outside the i loop, or just do one row vector at a time.
Your random numbers are currently in the range 3 to 11, not 3 to 9.
Last edited on
Hi lastchance and helios, thank you for your advise.
I’ve improved this codes based on your explanation and it worked. Thank you so much for helping. I really appreciated it.
Topic archived. No new replies allowed.
13 Years Ago
Hi!
I try to implement a matrix template class which inherits the vector of vectors.
The message I get: «error C2679: binary ‘=’ : no operator found which takes a right-hand operand of type ‘const Vector<T> *’ (or there is no acceptable conversion)» (When I call the alternate matrix constructor, at the line «this = &h;».)
Any thoughts…? Thanks a lot in advance.
vectorTemplate.h:
#ifndef _VECTOR_TEMPLATE_H
#define _VECTOR_TEMPLATE_H
#include <iostream>
#include <fstream>
//#include "complex.h"
template<class T>
class Vector
{ private:
int num; // Number of elements
T* pdata; // Pointer to the data
void Init(int Num); // private function since user should not call it
// only for the member functions to call
public:
Vector(); // default constructor
Vector(int Num); // alternate constructor
Vector(const Vector& v); // copy constructor
~Vector(); // destructor
int GetNum() const; // access function
Vector<T>& operator= (const Vector<T>& v); // overloaded assignment operator
T& operator[] (int i) const; // overloaded array access operator
template<class T> friend std::istream& operator>>(std::istream& is, Vector<T>& v);// keyboard input
template<class T> friend std::ostream& operator<<(std::ostream& os, Vector<T>& v);// screen output
template<class T> friend std::ifstream& operator>>(std::ifstream& ifs, Vector<T>& v);// file input
template<class T> friend std::ofstream& operator<<(std::ofstream& ofs, Vector<T>& v);// file output
};
// default constructor
template<class T>
Vector<T>::Vector() : num(0), pdata(0) {}
// initialise data, called by the constructors
template<class T>
void Vector<T>::Init(int Num)
{
num = Num;
if (num <= 0)
pdata = 0; // Object construction failed!
else
pdata = new T[num]; // Allocate memory for vector
}
// alternate constructor
template<class T>
Vector<T>::Vector(int Num)
{
Init(Num);
}
// copy constructor
template<class T>
Vector<T>::Vector(const Vector& copy) {
Init(copy.GetNum()); // allocate the memory
// copy the data members
if (pdata) for (int i=0; i<num; i++) pdata[i]=copy.pdata[i];
}
// destructor
template<class T>
Vector<T>::~Vector()
{
delete [] pdata; // free the dynamic memory
}
// assignment operator
template<class T>
Vector<T>& Vector<T>::operator=(const Vector& copy)
{
if (this == ©) return *this; // Can't copy self to self (that is v = v
// in main is dealt with)
delete [] pdata; // delete existing memory
Init(copy.GetNum()); // create new memory then copy data
if (pdata) for (int i=0; i<copy.GetNum(); i++) pdata[i] = copy.pdata[i];
return *this;
}
// array access operator
template<class T>
T& Vector<T>::operator[](int i) const
{
if (i < 0)
i = 0; // Range error causes index to equal 0
// should really throw an exception
return pdata[i];
}
// return the size of the vector
template<class T>
int Vector<T>::GetNum() const
{
return num;
}
// keyboard input
template<class T>
std::istream& operator>>(std::istream& is, Vector<T>& v) {
int Num;
std::cout << "input the size for the vectorn";
is >> Num;
// create a temporary Vector object of correct size
Vector<T> temp(Num);
// input the elements
std::cout << "input the vector elementsn";
for (int i=0; i<Num; i++) is >> temp[i];
// copy temp into v
v = temp;
// return the stream object
return is;
}
// file input
template<class T>
std::ifstream& operator>>(std::ifstream& ifs, Vector<T>& v)
{
int Num;
// read size from the file
ifs >> Num;
// create a temporary Vector object of correct size
Vector<T> temp(Num);
// input the values
for (int i=0; i<Num; i++) ifs >> temp[i];
// copy temp into v
v = temp;
// return the file stream object
return ifs;
}
// screen output
template<class T>
std::ostream& operator<<(std::ostream& os, Vector<T>& v)
{
if (v.pdata) {
os << "The vector elements aren";
for (int i=0; i<v.GetNum(); i++) os << v[i] << "n";
}
return os;
}
// file output
template<class T>
std::ofstream& operator<<(std::ofstream& ofs, Vector<T>& v)
{
if (v.pdata) {
ofs << "The vector elements aren";
for (int i=0; i<v.GetNum(); i++) ofs << v[i] << "n";
}
return ofs;
}
#endif
matrixTemplate.h:
#ifndef _MATRIX_TEMPLATE_H
#define _MATRIX_TEMPLATE_H
#include <iostream>//
#include <fstream>//
#include "vectorTemplate.h"
//#include "complex.h"
template<class T>
class Matrix : public Vector< Vector<T> >{
public:
Matrix(); // default constructor, uses default constructor for v
Matrix(int Nrows, int Ncols); // alternate constructor
//T& operator() (int i, int j) const; // function call overload (-,-)
template<class T> friend Matrix<T> operator*(const Matrix<T>& m1, const Matrix<T>& m2); // overload * for matrix multiplication
template<class T> friend std::istream& operator>>(std::istream& is, Matrix<T>& m);// keyboard input
template<class T> friend std::ostream& operator<<(std::ostream& os, Matrix<T>& m);// screen output
template<class T> friend std::ifstream& operator>>(std::ifstream& ifs, Matrix<T>& m);// file input
template<class T> friend std::ofstream& operator<<(std::ofstream& ofs, Matrix<T>& m);// file output
};
template<class T>
Matrix<T>::Matrix() : Vector< Vector<T> >()/*, nrows(0), ncols(0)*//*, Vector() */{}// default constructor, uses default constructor for v
template<class T>
Matrix<T>::Matrix(int Nrows, int Ncols) : Vector< Vector<T> >(Nrows)/*Vector< Vector<T> >()*//*, nrows(Nrows)*//*, ncols(Ncols)*//*, Vector(Nrows)*/ // alternate constructor
{
for (int i = 0; i < Nrows; i++)
{
/*const Vector<T>* d = new Vector<T>(Ncols);
this[i] = d;*/
Vector<T>* d = new Vector<T>(Ncols);
const Vector<T> h = *d;
this[i] = &h;
//this[i] = new Vector<T>(Ncols);
//this[i] = *(new Vector<T>(Ncols));//this[i] = &(*(new Vector<T>(Ncols)));//this[i] = *(new Vector<T>(Ncols));
}
}
template<class T>
Matrix<T> operator*(const Matrix<T>& m1, const Matrix<T>& m2)
// overload * for matrix multiplication
{
if (m1[0].GetNum() == m2.GetNum())
{
Matrix<T> m3(m1.GetNum() , m2[0].GetNum());
for (int i = 0; i < m1.GetNum(); i++)
{
for (int j = 0; j < m2[0].GetNum(); j++)
{
for (int k = 0; k < m1[0].GetNum(); k++)
{
if (k == 0) m3[i][j] = m1[i][k] * m2[k][j];
else m3[i][j] = m3[i][j] + m1[i][k] * m2[k][j];
}
}
}
return m3;
}
else
{
std::cout << "input matrices are not multicablen";
return m1;
}
}
//screen input
template<class T>
std::istream& operator>>(std::istream& is, Matrix<T>& m) {
int Nrows, Ncols;
// input the size of the matrix
std::cout << "input num of rows and columnsn";
is >> Nrows >> Ncols;
// create a temporary matrix of the correct size
Matrix<T> temp(Nrows, Ncols);
std::cout << "input the matrix elementsn";
for (int i=0; i<Nrows; i++)
{
for (int j=0 ; j<Ncols; j++)
{std::cout << "hi";
is >> temp[i][j];std::cout << "ha";
}
}
// copy temp to m
m = temp;
return is;
}
// file input
template<class T>
std::ifstream& operator>>(std::ifstream& ifs, Matrix<T>& m)
{
int Nrows, Ncols;
// read size from the file
ifs >> Nrows >> Ncols;
// create a temporary Matrix object of correct size
Matrix<T> temp(Nrows, Ncols);
// input the values
for (int i=0; i<Nrows; i++)
for (int j=0 ; j<Ncols; j++) ifs >> temp[i][j];
// copy temp to m
m = temp;
// return the file stream object
return ifs;
}
// screen output
template<class T>
std::ostream& operator<<(std::ostream& os, Matrix<T>& m)
{
if (m.GetNum() > 0) {
os << "The matrix elements aren";
for (int i=0; i<m.GetNum(); i++)
{
if (m[0].GetNum() > 0)
{
for (int j=0; j<m[0].GetNum(); j++)
{
os << m[i][j] << "n";
}
}
}
}
return os;
}
// file output
template<class T>
std::ofstream& operator<<(std::ofstream& ofs, Matrix<T>& m)
{
if (m.GetNum() > 0) {
ofs << "The matrix elements aren";
for (int i=0; i<m.GetNum(); i++)
{
if (m[0].GetNum() > 0)
{
for (int j=0; j<m[0].GetNum(); j++)
{
ofs << m[i][j] << "n";
}
}
}
}
return ofs;
}
#endif
Recommended Answers
Can you explain why did you wrote this absolutely senseless expression:
this[i] = &h
? If you want inheritedoperator[]
, write(*this)[i]
…
Jump to Post
It’s of no importance. What did you want to do there — that is a question.
Jump to Post
All 5 Replies
ArkM
1,090
Postaholic
13 Years Ago
Can you explain why did you wrote this absolutely senseless expression: this[i] = &h
? If you want inherited operator[]
, write (*this)[i]
…
13 Years Ago
Can you explain why did you wrote this absolutely senseless expression:
this[i] = &h
? If you want inheritedoperator[]
, write(*this)[i]
…
I tried many combinations (some of them are still there as comments), among them this[i] = new Vector<T>(Ncols);
too. (*this)[i] = new Vector<T>(Ncols);
is not working either.
ArkM
1,090
Postaholic
13 Years Ago
It’s of no importance. What did you want to do there — that is a question.
daviddoria
334
Posting Virtuoso
Featured Poster
13 Years Ago
Why post 500 lines of code? Can you simplify the code to < 20 lines so we can look at it?
xth
0
Newbie Poster
12 Years Ago
how did you solve the problem?
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Ошибки компилирования Visual studio 2010
, error C2679: бинарный «<<«: не найден оператор, принимающий правый операнд типа «void»
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
С++ начал токо изучать по книги и при попытке напечать один из примеров выдала Visual Studio 2010 выдал ошибку и скомпилировать не смог. Цитата groundhog Объясню, что написл Slip — cout не перегружен для работы с void-типами, и это нормально, это в логике вещей, нельзя вывести то, чего нет. А твоя функция возвращает void тип, который ты и пытаешься вывести. Следовательно, чтобы убрать эту ошибку нужно вызывать твою функцию вне cout; И сообственно как мне сделать так что бы эта тестовая программа у меня заработала?
#include <iostream> #include <string> using namespace std; class studentList { public: //структура studentList (string name) { setInstitutName (name); } //три функции void setInstitutName(string name) { institutName = name; } string getInstitutName() { return institutName; } void displayInstitutName() { cout << getInstitutName() << endl; } private: string institutName; }; int main () { studentList student1 ( «one» ); studentList student2 ( «two» ); cout << student1.displayInstitutName() << student2.displayInstitutName() << endl; //здесь ошибка system(«pause»); return 0; } —— Построение начато: проект: firstProgram, Конфигурация: Debug Win32 —— …. c:program files (x86)microsoft visual studio 10.0vcincludeostream(487): или «std::basic_ostream<_Elem,_Traits> &std::basic_ostream<_Elem,_Traits>::operator <<(std::basic_streambuf<_Elem,_Traits> *)» СБОЙ построения. Затраченное время: 00:00:02.20 Сообщение отредактировано: FIZy — 05.10.10, 21:36 |
B.V. |
|
Ну, так убери эту строчку, и оставь только вызовы функций
cout << student1.displayInstitutName() << student2.displayInstitutName() << endl; //здесь ошибка Или перепиши displayInstitutName, что бы она ничего не выводила и возвращала результат в basic_string |
FIZy |
|
И вправду убрал тип void у displayInstitutName и сказал возратить значение)
string displayInstitutName() { return getInstitutName(); } 2B.V. Спасибо) Добавлено 05.10.10, 22:01
#include <iostream> #include <string> using namespace std; class studentList { public: //структура studentList (string name) { setInstitutName (name); } //три функции void setInstitutName(string name) { institutName = name; } string getInstitutName() { return institutName; } void displayInstitutName() { cout << getInstitutName(); } private: string institutName; }; int main () { studentList student1 ( «one» ); studentList student2 ( «two» ); student1.displayInstitutName(); student2.displayInstitutName(); system(«pause»); return 0; } Сообщение отредактировано: FIZy — 05.10.10, 22:02 |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Visual C++ / MFC / WTL
- Следующая тема
[ Script execution time: 0,0411 ] [ 16 queries used ] [ Generated: 9.02.23, 12:12 GMT ]