#c #visual-c
#c #visual-c
Вопрос:
Это довольно простой материал, который я делал раньше, но я не понимаю, почему у меня сейчас проблема. Я создаю объект ‘foo’ для простого взаимодействия с iostream activity для файлов и из них.
Я построил почти весь проект без каких-либо проблем до сегодняшнего дня, когда я добавил пару методов, которые, похоже, имеют проблемы, обнаруживаемые в контексте файла определения.
foo.h:
#ifndef FOO_H
#define FOO_H
#include <string>
#include <fstream>
#include <vector>
using std::string;
using std::fstream;
using std::vector;
namespace FileSys
{
class foo
{
public:
foo();
/**
* Attempts to open a file from directory dir
* @param dir
* The path of the file to be opened
*/
foo( string dir );
/**
* Attempts to find a directory using the parent file's path as the root directory and extending the directory by the child string
* If child is null, the foo is replicated. Fails when parent.isDirectory() returns false.
* @param parent
* The parent file to be used as the root path
* @param child
* The child path to be used for extending the parent path
*/
foo( foo amp;parent, string child );
/**
* Attempts to find a directory using the parent path as the root directory and extending the directory by the child string
* If child is null, the foo is created with the parent path as the full path.
* @param parent
* The parent path to be used as the root path
* @param child
* The child path to be used for extending the parent path
*/
foo( string parent, string child );
/**
* Attempts to clone reference to a previously existing foo file
* @param file
* The file to be cloned
*/
foo( foo amp;file );
/**
* Returns the working directory of this file
*/
string getDir();
/**
* Writes the content supplied to the file, overwriting any existing data
*/
bool writeTrunc( string content );
/**
* Writes the content supplied to the file, appending it to the end of the file
*/
bool writeApp( string content );
/**
* Concatenates two files together. No implementation yet.
*/
bool concatFiles( foo file1, foo file2 );
/**
* Reads from file
*
* @param length
* How many bytes will be retrieved from the file
*/
string read( int length );
/**
* Reads from file
*
* @param length
* How many bytes will be retrieved from the file
*
* @param position
* Position to start reading from
*/
string read( int length, int position );
/**
* Returns everything from the file
*/
string readWholeFile();
/**
* Returns true if the file exists
*/
bool exists();
/**
* Attempts to delete the current file
* @return Returns true if successful and false otherwise
* The path of the file to be opened
*/
bool deleteFile();
/**
* Returns true if this foo is a directory, rather than a file
*/
bool isDirectory();
/**
* Returns the absolute path of the foo
*/
string getAbsolutePath();
/**
* Returns the parent directory of this foo
*/
foo getParentFile();
/**
* Creates all non-existent folders in mPath, creating the directory for this foo.
*/
bool mkdirs();
/**
* Clean the file attributes
*/
bool cleanFile();
/**
* Returns a list of all the directories and files contained within this directory
*/
vector<foo> list();
/**
* Deletes the file or directory from the file system
*/
bool destroy();
/**
* Overrides the '=' operator to perform an assignment properly
*/
fooamp; operator=(foo amp;file);
/**
* Overrides the '==' operator to perform an equality comparison on two foo
*/
bool operator==(foo amp;file);
/**
* Overrides the '!=' operator to perform an inequality comparison on two foo
*/
bool operator!=(foo amp;file);
~foo();
protected:
private:
string mPath;
fstream mFile;
bool mExists;
bool mIsFile;
/**
* Opens the file for operation
*
* @param openMode
* The mode the file should be opened in. Use ios::openmode modes to determine the open mode.
*
* @return Returns true if successfully opened and false if failed
*/
bool openFile( int openMode );
/**
* Indicates whether this foo is a file or a directory
* Returns true if a file and false if a directory.
*/
bool isFile();
/**
* Checks to see if the directory exists and attempts to create it if its parents exist
*
* @param dir
* The directory to be created
*
* @return Returns true if successful
*/
bool mkdirs( foo dir );
};
}
#endif // foo_H
foo.cpp:
#include "foo.h"
#include <string>
#include <fstream>
#include <vector>
#include <errno.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#include <sys/stat.h>
using std::string;
using std::fstream;
using std::vector;
#ifdef _WIN32
#include <direct.h>
using namespace std;
#define mkdir(path,mode) _mkdir(path)
#define getcwd _getcwd
#endif
#define ROOT_WORKING_DIRECTORY "SomeDir"
namespace FileSys
{
////////////////////////////////////////////
// Ctors
////////////////////////////////////////////
foo::foo()
{ /*implementation*/ }
foo::foo( string dir )
{ /*implementation*/ }
foo::foo( foo amp;file )
{ /*implementation*/ }
foo::foo( foo amp;parent, string child )
{ /*implementation*/ }
foo::foo( string parent, string child )
{ /*implementation*/ }
////////////////////////////////////////////
// Public methods
////////////////////////////////////////////
string foo::getDir()
{ /*implementation*/ }
bool foo::deleteFile()
{ /*implementation*/ }
bool foo::exists()
{ /*implementation*/ }
bool foo::writeApp( string content )
{ /*implementation*/ }
bool foo::writeTrunc( string content )
{ /*implementation*/ }
string foo::read( int length )
{ /*implementation*/ }
string foo::read( int length, int position )
{ /*implementation*/ }
string foo::readWholeFile()
{ /*implementation*/ }
bool foo::isDirectory()
{ /*implementation*/ }
string foo::getAbsolutePath()
{ /*implementation*/ }
foo foo::getParentFile()
{ /*implementation*/ }
bool foo::mkdirs()
{ /*implementation*/ }
fooamp; foo::operator=(foo amp;file)
{ /*implementation*/ }
bool foo::operator==(foo amp;file) //err 2039: 'operator==' is not a member of foo
{ /*implementation*/ }
bool foo::operator!=(foo amp;file) //err 2039: 'operator!=' is not a member of foo
{ /*implementation*/ }
bool foo::cleanFile()
{ /*implementation*/ }
vector<foo> foo::list() //err 2039: 'list' is not a member of foo
{ /*implementation*/ }
bool foo::destroy() //err 2039: 'destroy' is not a member of foo
{ /*implementation*/ }
////////////////////////////////////////////
// Private methods
////////////////////////////////////////////
bool foo::openFile( int openMode )
{ /*implementation*/ }
bool foo::isFile()
{ /*implementation*/ }
bool foo::mkdirs( foo dir )
{ /*implementation*/ }
////////////////////////////////////////////
// Dtors
////////////////////////////////////////////
foo::~foo()
{ /*implementation*/ }
}
Любые подсказки относительно того, что я сделал, чтобы создать эту проблему?
Редактировать: я включил реальный код, изменив только сигнатуру класса и удалив реализации. Я трижды проверил синтаксис, чтобы убедиться, что я не ошибся в имени класса в разрешении области действия методов, которые не работают.
Комментарии:
1. Вероятно, вы где-то допустили опечатку, но мы не можем сказать, потому что вы не опубликовали реальный код.
2. Вы уверены, что
destroy
ни в одном из ваших заголовочных файлов нет определения препроцессора для? Попробуйте#undef destroy
перед определением.3. @DeepYellow, если бы был макрос, переименовывающий функцию, это было бы отражено в сообщении об ошибке.
4. Привет, @nukeforum. Добро пожаловать в Stack Overflow . Вы получите более полезные ответы, если опубликуете код, который на самом деле демонстрирует проблему, с которой вы столкнулись. Вы опубликовали псевдокод, а сообщения об ошибке нет. Пожалуйста, сократите свою программу с ошибкой до минимально возможной программы, которая все еще демонстрирует проблему, и скопируйте и вставьте эту минимальную программу в свой вопрос. Для получения дополнительной информации см. sscce.org .
5. @MarkRansom, ты правильно подметил. Но когда все действительно странно, стоит исключить препроцессор как виновника. Рассмотрим, например, если более раннее включение определяет
destroy
так, что оно определено для заголовка, но более позднее включение защитно отменяет его. Маловероятно? Да, но я видел незнакомца!
Ответ №1:
Мы не можем знать (потому что вы не опубликовали настоящий C ), но мой хрустальный шар говорит:
У вас есть две копии «foo.h». Тот, который вы отредактировали, не является тем, который обнаруживается #include
директивой.
Комментарии:
1. Я тоже думал об этом, но я сохранил оба файла, открыл их из каталога проекта в отдельном редакторе файлов, и они оба отразили самые последние изменения.
Ответ №2:
Если я добавлю соответствующие операторы возврата в опубликованный вами код, он будет скомпилирован.
Я все еще думаю, что наиболее вероятной причиной является где-то опечатка — если вы не можете показать нам точный код, который пытаетесь скомпилировать, найдите кого-нибудь, кому вы можете показать код, и попросите их перепроверить его для вас.