Source.cpp
#include <string>
#include <iostream>
#include <conio.h>
#include "Hospital.h"
#include "Patient.h"
using namespace std;
int main()
{
char strHospital[25], strSpecialization[25], strCity[25], strSurename[25], strName[25], strPatronymic[25], strDepartment[25], strDisease[25];
int iMonth, iDay, iYear;
char chKey1, chKey2, chRep;
do {
cout << "Do you want to know a Hospital information?" << endl;
cout << "Y//N" << endl;
cin >> chKey1;
if (chKey1 == 'Y' || chKey1 == 'y')
{
cout << "Please enter a Hospital data:" << endl;
cout << endl;
cout << "Enter hospital name - ";
cin >> strHospital;
cout << "Enter specialization - ";
cin >> strSpecialization;
cout << "Enter city - ";
cin >> strCity;
cout << endl;
Hospital objHospital(strHospital, strSpecialization, strCity);
objHospital.Show();
}
cout << "Do you want to know a Patient information?" << endl;
cout << "Y//N" << endl;
cin >> chKey2;
if (chKey2 == 'Y' || chKey2 == 'y')
{
cout << "Please enter a Patient data:" << endl;
cout << endl;
cout << "Enter patient Surename - ";
cin >> strSurename;
cout << "Enter patient Name - ";
cin >> strName;
cout << "Enter patient Patronymic - ";
cin >> strPatronymic;
cout << "Enter patient Department - ";
cin >> strDepartment;
cout << "Enter patient Disease - ";
cin >> strDisease;
cout << "Enter patient Date of Birth(Day, Month, Year) - ";
cin >> iDay;
cin >> iMonth;
cin >> iYear;
Patient objPatient(strSurename, strName, strPatronymic, strDepartment, strDisease, iMonth, iDay, iYear);
objPatient.ShowPatient();
}
cout << "Do you want to work with programm again?" << endl;
cout << "Y//N" << endl;
cin >> chRep;
} while (chRep == 'Y' || chRep == 'y');
system("PAUSE");
return 0;
}
Hospital.h
#include <string>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
using namespace std;
// створення класу
class Hospital
{
private:
string strHospital, strSpecialization, strCity; // опис змінних
public:
// Конструктор за умовчанням
Hospital() {};
// Конструктор опису змінних
Hospital(char* chHospital, char* chSpecialization, char* chCity);
// Конструктор копіювання
Hospital(const Hospital &Hosp) {
this->strHospital = Hosp.strHospital;
this->strSpecialization = Hosp.strSpecialization;
this->strCity = Hosp.strCity;
}
//сетери
void setHospital (char* chHospital);
void setSpecialization (char* chSpecialization);
void setCity (char* chCity);
//гетери
string getHospital(void) { return strHospital; }
string getSpecialization(void) { return strSpecialization; }
string getCity(void) { return strCity; }
// перевірити правильність введення слів у введених даних
bool isValidAllName(char*);
//вивід
void Show();
//віртуальний деструктор
virtual ~Hospital() {}
};
//Конструктори
Hospital::Hospital(char* chHospital, char* chSpecialization, char* chCity) {
setHospital(chHospital);
setSpecialization(chSpecialization);
setCity(chCity);
}
// перевірка назви
bool Hospital::isValidAllName(char* word)
{
char simvol = word[0];
if (simvol >= 65 && simvol <= 104 || simvol >= 192 && simvol <= 223)
return true;
else return false;
}
//Вивід класу
void Hospital::Show() {
cout << "Hospital Info:" << endl;
cout << "|" << strHospital << "|" << strSpecialization << "|" << strCity << "|" << endl;
}
// ввести назву лікарні
void Hospital::setHospital(char* Hospital)
{
bool b = isValidAllName(Hospital);
try
{
if (b)
{
this->strHospital = Hospital; // Запис значення chHospital
}
else throw b;
}
catch (bool b) // ловимо виключення
{
cout << "Not valid Name!" << Hospital << endl;
this->strHospital = "no name";
}
}
// ввести назву спеціалізації
void Hospital::setSpecialization(char* Specialization)
{
bool b = isValidAllName(Specialization);
try
{
if (b)
{
this->strSpecialization = Specialization; // Запис значення chSpecialization
}
else throw b;
}
catch (bool b) // ловимо виключення
{
cout << "Not valid Name!" << Specialization << endl;
this->strSpecialization = "no name";
}
}
// ввести назву міста
void Hospital::setCity(char* City)
{
bool b = isValidAllName(City);
try
{
if (b)
{
this->strCity = City; // Запис значення chCity
}
else throw b;
}
catch (bool b) // ловимо виключення
{
cout << "Not valid Name!" << City << endl;
this->strCity = "no name";
}
}
Patient.h
#include <string>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
using namespace std;
/*-----------------------------------ПОХІДНИЙ КЛАС--------------------------------*/
// створення похідного класу
class Patient : public Hospital
{
private:
string strSurename, strName, strPatronymic, strDepartment, strDisease;
int iMonth, iDay, iYear;
public:
// Конструктор за умовчанням
Patient() {};
// Конструктор опису змінних
Patient(char* chSurename, char* chName, char* chPatronymic, char* chDepartment, char* chDisease, int iMonth , int iDay, int iYear);
// Конструктор копіювання
Patient(const Patient &Pat, const Hospital &other) :Hospital(other)
{
setPatient((char*)Pat.strSurename.c_str(), (char*)Pat.strName.c_str(), (char*)Pat.strPatronymic.c_str());
setDepartment((char*)Pat.strDepartment.c_str());
setDisease((char*)Pat.strDisease.c_str());
setMonth((int)Pat.iMonth);
setDay((int)Pat.iDay);
setYear((int)Pat.iYear);
}
//сетери
void setSurename(char* chSurename) { this->strSurename = chSurename; }
void setName(char* chName) { this->strName = chName; }
void setPatronymic(char* chPatronymic) { this->strPatronymic = chPatronymic; }
void setDepartment(char* chDepartment) { this->strDepartment = chDepartment; }
void setDisease(char* chDisease) { this->strDisease = chDisease; }
void setMonth(int iMonth) { this->iMonth = iMonth; }
void setDay(int iDay) { this->iDay = iDay; }
void setYear(int iYear) { this->iYear = iYear; }
void setPatient(char* chSurename, char* chName, char* chPatronymic)
{
this->strSurename = chSurename;
this->strName = chName;
this->strPatronymic = chPatronymic;
}
//гетери
string getSurename(void) const { return strSurename; }
string getName(void) const { return strName; }
string getPatronymic(void) const { return strPatronymic; }
string getDepartment(void) const { return strDepartment; }
string getDisease(void) const { return strDisease; }
int getMonth(void) const { return iMonth; }
int getDay(void) const { return iDay; }
int getYear(void) const { return iYear; }
string getPatient(void) const { return strSurename + " " + strName + " " + strPatronymic; }
//методи
void ShowPatient();
bool isValidAllName(char*);
//віртуальний деструктор
virtual ~Patient();
};
/*-------------------------------------МЕТОДИ----------------------------------------*/
//конструктор з параметрами
Patient::Patient(char* chSurename, char* chName, char* chPatronymic, char* chDepartment, char* chDisease, int iMonth, int iDay, int iYear)// : Hospital(chHospital, chSpecialization, chCity)
{
setPatient(chSurename, chName, chPatronymic);
setDepartment(chDepartment);
setDisease(chDisease);
setMonth(iMonth);
setDay(iDay);
setYear(iYear);
}
//Вивід класу
void Patient::ShowPatient() {
cout << "Patient Info: " << endl;
cout << "S.N.P: " << getPatient() << endl;
cout << "Department: " << getDepartment() << endl;
cout << "Disease: " << getDisease() << endl;
cout << "Date of Birth: " << getDay() << "." << getMonth() << "." << getYear() << endl;
}
// перевірка назви
bool Patient::isValidAllName(char* word)
{
char simvol = word[0];
if (simvol >= 65 && simvol <= 104 || simvol >= 192 && simvol <= 223)
return true;
else return false;
}
inline Patient::~Patient()
{
}
Скрины с описанием ошибок:
1
2
Всем спасибо за ответы.)Проблема решена.
soa432 0 / 0 / 0 Регистрация: 09.12.2012 Сообщений: 18 |
||||
1 |
||||
03.02.2013, 02:47. Показов 3764. Ответов 1 Метки нет (Все метки)
Не могу понять в чем ошибка, все из-за того что поменял компилятор, старый работал нормально, никаких ошибок не выдавал. Сейчас VS 2012
0 |
MrGluck Форумчанин 8194 / 5044 / 1437 Регистрация: 29.11.2010 Сообщений: 13,453 |
||||
03.02.2013, 03:09 |
2 |
|||
warning т.к. в int записывался std::size_t (unsigned), соответственно могла быть ошибка при преобразовании.
1 |
Учу WinApi, задали написать файловый менеджер.
#include "pch.h"
#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>
using namespace std;
int main()
{
HANDLE hFindFile, hFile;
WIN32_FIND_DATA fd, file_inf[100];
int i, counter;
counter = 0;
string comand, directory, prev, file_name, user_path, addition[100];
directory = "D:\";
prev = "D:\";
bool x = true;
i = 0;
while (true) {
cout << "help to see all comands" << endl;
cin >> comand;
if (comand == "help") {
cout << "dir - show all files in current directory" << endl;
cout << "cd - enter directory" << endl;
cout << "kill - delete file" << endl;
cout << "text - create file" << endl;
cout << "copy - copy file" << endl;
}
if (comand == "dir") {
cout << "_____________" << endl;
hFindFile = FindFirstFile ((directory + "*.*").c_str(), &fd);
file_inf[0] = fd;
while (FindNextFile(hFindFile, &fd)) {
i++;
file_inf[i] = fd;
}
int n = i;
for (i = 0; i <= n - 1; i++) {
cout << file_inf[i].cFileName << endl;
}
cout << "_____________" << endl;
i = 0;
}
if (comand == "cd") {
cout << "directory name?" << endl;
cin >> addition[counter];
if (addition[counter] == "..") {
counter--;
directory = prev;
}
else {
counter++;
}
for (int i = 0; i < counter; i++) {
directory += "\" + addition[i] + "\";
}
cout << directory << endl;
}
if (comand == "kill") {
cout << "file's name?" << endl;
cin >> file_name;
hFindFile = FindFirstFile((directory + file_name + "*.*").c_str(), &fd);
file_inf[0] = fd;
cout << directory + file_name << endl;
DeleteFile((directory + file_inf[0].cFileName).c_str());
}
if (comand == "create") {
cout << "file's name?" << endl;
cin >> file_name;
hFile = CreateFile((directory + file_name).c_str(),
GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
CloseHandle(hFile);
}
if (comand == "copy") {
cout << "file's name?" << endl;
cin >> file_name;
cout << "new folder?" << endl;
cin >> user_path;
CopyFile((directory + file_name).c_str(), (user_path + file_name).c_str(), false);
}
}
system("pause");
return 0;
}
Выдает 4 ошибки по типу: C2664 «HANDLE FindFirstFileW(LPCWSTR,LPWIN32_FIND_DATAW)»: невозможно преобразовать аргумент 1 из «const _Elem *» в «LPCWSTR». Подскажите как быть?
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2664 |
Compiler Error C2664 |
11/04/2016 |
C2664 |
C2664 |
3595d66e-cf87-4fda-a896-c0cd81f95db4 |
Compiler Error C2664
‘function’ : cannot convert argument n from ‘type1’ to ‘type2’
This parameter conversion problem might happen if an instance of a class is created and an implicit conversion is attempted on a constructor marked with the explicit
keyword. For more information about explicit conversions, see User-Defined Type Conversions.
If a temporary object is passed to a function that takes a reference to an object as a parameter, that reference must be a const
reference.
If the function is passed a parameter that is not of the type that the function expects, a temporary object is created by using the appropriate constructor. This temporary object is then passed to the function. In this case, the temporary object is used to initialize the reference. In earlier versions of the language, all references could be initialized by temporary objects.
To fix C2664,
-
Recheck the prototype for the given function and correct the argument noted in the error message.
-
Supply an explicit conversion if necessary.
C2664 can also be generated if a class hides a member in one of its base classes.
For more information, see How to: Convert System::String to wchar_t* or char*.
Examples
The following sample generates C2664 and shows how to fix it.
// C2664.cpp // C2664 struct A { void f(int i) {}; }; struct B : public A { // To fix, uncomment the following line. // using A::f; void f(A a) {}; }; int main() { B b; int i = 1; b.f(i); // B::f hides A::f Uncomment the using declaration in B. }
This sample also generates C2664 and shows how to fix it.
// C2664b.cpp // C2664 expected struct A { // To fix, uncomment the following line. // A(int i){} }; void func( int, A ) {} int main() { func( 1, 1 ); // No conversion from int to A. }
The next sample demonstrates C2664 by using a string literal to call Test
, and shows how to fix it. Because the parameter is an szString
reference, an object must be created by the appropriate constructor. The result is a temporary object that cannot be used to initialize the reference.
// C2664c.cpp // compile with: /EHsc // C2664 expected #include <iostream> #include <string.h> using namespace std; class szString { int slen; char *str; public: szString(const char *); int len() const { return slen; } }; // Simple reference cannot bind to temp var. void Test(szString &a) {} // To fix, uncomment the following line. // void Test(const szString &a) {} szString::szString(const char * newstr) : slen(0), str(NULL) { slen=strlen(newstr); str = new char[slen + 1]; if (str) strcpy_s(str, (slen + 1), newstr); } int main() { Test("hello"); }
The compiler enforces the C++ standard requirements for applying const
. This sample generates C2664:
// C2664d.cpp // C2664 expected #include <windows.h> void func1(LPCSTR &s) { } void func2(LPSTR &s) { func1(s); } int main() { return 0; }
Here’s a more complex situation where C2664 is generated, including directions on how to fix it:
// C2664e.cpp // compile with: /EHsc // C2664 expected #define _INTL #include <locale> #include <iostream> using namespace std; #define LEN 90 int main( ) { char* pszExt = "This is the string to be converted!"; wchar_t pwszInt [LEN+1]; memset(&pwszInt[0], 0, (sizeof(wchar_t))*(LEN+1)); // To fix, delete the following line. char* pszNext; // To fix, uncomment the following line. // const char* pszNext; wchar_t* pwszNext; mbstate_t state; locale loc("C"); int res = use_facet<codecvt<wchar_t, char, mbstate_t> > ( loc ).in( state, pszExt, &pszExt[strlen(pszExt)], pszNext, pwszInt, &pwszInt[strlen(pszExt)], pwszNext ); // See earlier comment. pwszInt[strlen(pszExt)] = 0; wcout << ( (res!=codecvt_base::error) ? L"It worked! " : L"It didn't work! " ) << L"The converted string is:n [" << &pwszInt[0] << L"]" << endl; exit(-1); }
An enum variable is not converted to its underlying type such that a function call will be satisfied. For more information, see enum class. The following sample generates C2664 and shows how to fix it.
// C2664f.cpp // compile with: /clr using namespace System; public enum class A : Char { None = 0, NonSilent = 1, }; void Test(Char c) {} int main() { A aa = A::None; Test(aa); // C2664 Test(Char(aa)); // OK - fix by using a conversion cast }
A bug in the midl compiler causes a wchar_t type to be emitted as an unsigned short in the type library. To resolve this error, either cast the type in your C++ source code or define the type as a string in the idl file.
// C2664g.idl
import "prsht.idl";
[ object, uuid(8402B8F1-BF7F-4B49-92D4-C2B9DF4543E9) ]
interface IMyObj1 : IUnknown {
HRESULT teststr([in, string] wchar_t *wstr);
HRESULT testarr([in, size_is(len)] wchar_t wstr[], [in] int len);
HRESULT testbstr([in] BSTR bstr);
};
[ uuid(44463307-CBFC-47A6-8B4F-13CD0A83B436) ]
library myproj1 {
[ version(1.0), uuid(D8622C12-5448-42B8-8F0E-E3AD6B8470C1) ]
coclass CMyObj1 { interface IMyObj1; };
}
C2664 is also raised by using wchar_t
when porting code from Visual C++ 6.0 to later versions. In Visual C++ 6.0 and earlier, wchar_t
was a typedef
for unsigned short
and was therefore implicitly convertible to that type. After Visual C++ 6.0, wchar_t
is its own built-in type, as specified in the C++ standard, and is no longer implicitly convertible to unsigned short
. See /Zc:wchar_t (wchar_t Is Native Type).
The following sample generates C2664 and shows how to fix it.
// C2664h.cpp #import "C2664g.tlb" using namespace myproj1; int main() { IMyObj1Ptr ptr; wchar_t * mybuff = 0; BSTR bstr = 0; int len; ptr->teststr(mybuff); ptr->testbstr(bstr); ptr->testarr(mybuff, len); // C2664 ptr->testarr((unsigned short *)mybuff, len); // OK - Fix by using a cast }
C2664 is also caused if the compiler cannot deduce template arguments.
// C2664i.cpp #include <stdio.h> template <class T, int iType=0> class CTypedImg { public: CTypedImg() {} void run() {} operator CTypedImg<T>& () { return *((CTypedImg<T>*)this); } }; template <class t1> void test(CTypedImg<t1>& myarg) { myarg.run(); } int main() { CTypedImg<float,2> img; test((CTypedImg<float>&)img); // OK test<float>(img); // OK test(img); // C2664 - qualify as above to fix }
Я начал изучать Визуал Си недавно, так что не судите строго. Так вот, когда я компилирую программу (она у меня
консольная) оно выдает ошибку:
error C2664: ‘irc_privmsg’ : cannot convert parameter 2 from ‘const char [1]’ to ‘char *’
Вот в этой строке кода:
irc_privmsg(sock, channel, sendbuf, FALSE); выдается та ошибка
А вот как у меня объявлена irc_privmsg:
void irc_privmsg(SOCKET sock, char *dest, char *msg, BOOL notice);
Да, и *dest объявлена внутри структуры, как вы уже навероное поняли,вот так: char dest[128];
Собственно и второй параметр т.е channel: const char channel[] = «»;
Как я понял при компиляции оно не может конвертировать второй параметр irc_privmsg т.е channel. Они же у меня
все одинаковы т.е объявлены как char. В чем я ошибаюсь, подскажите а то я не понял.